package com.zhouxianglh.p36;

import java.util.Arrays;

/**
 * 36. 有效的数独
 * <p>
 * boolean 数组的使用
 *
 * @author zhouxianglh
 */
public class Solution {
    public static boolean isValidSudoku(char[][] board) {
        boolean[] rowSet = new boolean[9];
        boolean[] columnSet = new boolean[COUNT];
        boolean[] cellSet = new boolean[COUNT];
        for (int i = 0; i < COUNT; i++) {
            Arrays.fill(rowSet, false);
            Arrays.fill(columnSet, false);
            for (int j = 0; j < COUNT; j++) {
                int c = board[i][j] - START_NUM;
                if (NULL_NUM != c) {
                    if (rowSet[c]) {
                        return false;
                    } else {
                        rowSet[c] = true;
                    }
                }
                c = board[j][i] - START_NUM;
                if (NULL_NUM != c) {
                    if (columnSet[c]) {
                        return false;
                    } else {
                        columnSet[c] = true;
                    }
                }
            }

        }
        for (int i = 0; i < COUNT; i += CELL_COUNT) {
            for (int j = 0; j < COUNT; j += CELL_COUNT) {
                //
                Arrays.fill(cellSet, false);
                for (int m = 0; m < CELL_COUNT; m++) {
                    for (int n = 0; n < CELL_COUNT; n++) {
                        int c = board[i + m][j + n] - START_NUM;
                        if (NULL_NUM != c) {
                            if (cellSet[c]) {
                                return false;
                            } else {
                                cellSet[c] = true;
                            }
                        }
                    }
                }
            }
        }
        return true;
    }

    private static final int START_NUM = '1';

    private static final int COUNT = 9;

    private static final int CELL_COUNT = 3;

    private static final int NULL_NUM = '.' - '1';
}
